// store/index.ts
// 全局状态管理系统

/**
 * 用户信息接口
 * @typedef {Object} IUserInfo
 * @property {string} id
 * @property {string} nickName
 * @property {string} avatarUrl
 * @property {string} openId
 * @property {string} [unionId]
 * @property {boolean} isLoggedIn
 */

/**
 * 伴侣信息接口
 * @typedef {Object} IPartnerInfo
 * @property {string} id
 * @property {string} nickName
 * @property {string} avatarUrl
 * @property {'single'|'dating'|'married'} relationshipStatus
 * @property {string} [relationshipStartDate]
 */

/**
 * 情感状态接口
 * @typedef {Object} IEmotionStatus
 * @property {'happy'|'sad'|'angry'|'calm'} emotion
 * @property {string} emoji
 * @property {string} name
 * @property {number} intensity
 * @property {string} timestamp
 */

/**
 * 天气信息接口
 * @typedef {Object} IWeatherInfo
 * @property {number} temperature
 * @property {'sunny'|'cloudy'|'rainy'|'stormy'} condition
 * @property {string} description
 * @property {string} icon
 */

/**
 * 胶囊接口
 * @typedef {Object} ICapsule
 * @property {string} id
 * @property {string} title
 * @property {string} content
 * @property {IEmotionStatus} emotion
 * @property {string} coverUrl
 * @property {boolean} isLocked
 * @property {string} [unlockTime]
 * @property {string} createTime
 * @property {string} updateTime
 * @property {'text'|'voice'|'image'|'video'} type
 * @property {string[]} tags
 */

/**
 * 应用状态接口
 * @typedef {Object} IAppState
 * @property {IUserInfo} userInfo
 * @property {IPartnerInfo|null} partnerInfo
 * @property {IEmotionStatus} currentEmotion
 * @property {IWeatherInfo} emotionWeather
 * @property {ICapsule[]} capsules
 * @property {ICapsule|null} selectedCapsule
 * @property {boolean} isLoading
 * @property {'online'|'offline'} networkStatus
 * @property {'light'|'dark'|'auto'} theme
 * @property {Array} stealHistory
 * @property {*} stealTarget
 */

class AppStore {
  state
  listeners = []
  storageKey = 'lagain_app_state'

  constructor() {
    this.state = this.getInitialState()
    this.loadFromStorage()
  }

  /**
   * 获取初始状态
   */
  getInitialState() {
    return {
      userInfo: {
        id: '',
        nickName: '',
        avatarUrl: '',
        openId: '',
        isLoggedIn: false
      },
      partnerInfo: null,
      currentEmotion: {
        emotion: 'calm',
        emoji: '😌',
        name: '平静',
        intensity: 5,
        timestamp: new Date().toISOString()
      },
      emotionWeather: {
        temperature: 22,
        condition: 'sunny',
        description: '心情晴朗',
        icon: '☀️'
      },
      capsules: [],
      selectedCapsule: null,
      isLoading: false,
      networkStatus: 'online',
      theme: 'auto',
      stealHistory: [],
      stealTarget: null
    }
  }

  /**
   * 从本地存储加载状态
   */
  loadFromStorage() {
    try {
      const savedState = wx.getStorageSync(this.storageKey)
      if (savedState) {
        this.state = { ...this.state, ...savedState }
      }
    } catch (error) {
      console.error('Failed to load state from storage:', error)
    }
  }

  /**
   * 保存状态到本地存储
   */
  saveToStorage() {
    try {
      wx.setStorageSync(this.storageKey, this.state)
    } catch (error) {
      console.error('Failed to save state to storage:', error)
    }
  }

  /**
   * 获取当前状态
   */
  getState() {
    return { ...this.state }
  }

  /**
   * 订阅状态变化
   */
  subscribe(listener) {
    this.listeners.push(listener)
    
    // 返回取消订阅函数
    return () => {
      const index = this.listeners.indexOf(listener)
      if (index > -1) {
        this.listeners.splice(index, 1)
      }
    }
  }

  /**
   * 通知所有监听器
   */
  notify() {
    this.listeners.forEach(listener => {
      try {
        listener(this.getState())
      } catch (error) {
        console.error('Error in state listener:', error)
      }
    })
  }

  /**
   * 更新状态
   */
  setState(updater) {
    const updates = typeof updater === 'function' ? updater(this.state) : updater
    this.state = { ...this.state, ...updates }
    this.saveToStorage()
    this.notify()
  }

  // ========== 用户相关操作 ==========

  /**
   * 设置用户信息
   */
  setUserInfo(userInfo) {
    this.setState({
      userInfo: { ...this.state.userInfo, ...userInfo }
    })
  }

  /**
   * 用户登录
   */
  login(userInfo) {
    this.setState({
      userInfo: { ...userInfo, isLoggedIn: true }
    })
  }

  /**
   * 用户登出
   */
  logout() {
    this.setState({
      userInfo: this.getInitialState().userInfo,
      partnerInfo: null
    })
  }

  /**
   * 设置伴侣信息
   */
  setPartnerInfo(partnerInfo) {
    this.setState({ partnerInfo })
  }

  // ========== 情感相关操作 ==========

  /**
   * 更新当前心情
   */
  updateEmotion(emotion) {
    this.setState({
      currentEmotion: {
        ...this.state.currentEmotion,
        ...emotion,
        timestamp: new Date().toISOString()
      }
    })
  }

  /**
   * 更新情感天气
   */
  updateEmotionWeather(weather) {
    this.setState({
      emotionWeather: { ...this.state.emotionWeather, ...weather }
    })
  }

  // ========== 胶囊相关操作 ==========

  /**
   * 添加胶囊
   */
  addCapsule(capsule) {
    const newCapsule = {
      ...capsule,
      id: Date.now().toString(),
      createTime: new Date().toISOString(),
      updateTime: new Date().toISOString()
    }
    
    this.setState({
      capsules: [newCapsule, ...this.state.capsules]
    })
    
    return newCapsule
  }

  /**
   * 更新胶囊
   */
  updateCapsule(id, updates) {
    this.setState({
      capsules: this.state.capsules.map(capsule =>
        capsule.id === id
          ? { ...capsule, ...updates, updateTime: new Date().toISOString() }
          : capsule
      )
    })
  }

  /**
   * 删除胶囊
   */
  deleteCapsule(id) {
    this.setState({
      capsules: this.state.capsules.filter(capsule => capsule.id !== id),
      selectedCapsule: this.state.selectedCapsule?.id === id ? null : this.state.selectedCapsule
    })
  }

  /**
   * 选择胶囊
   */
  selectCapsule(capsule) {
    this.setState({ selectedCapsule: capsule })
  }

  /**
   * 解锁胶囊
   */
  unlockCapsule(id) {
    this.updateCapsule(id, {
      isLocked: false,
      unlockTime: new Date().toISOString()
    })
  }

  // ========== 应用状态操作 ==========

  /**
   * 设置加载状态
   */
  setLoading(isLoading) {
    this.setState({ isLoading })
  }

  /**
   * 设置网络状态
   */
  setNetworkStatus(networkStatus) {
    this.setState({ networkStatus })
  }

  /**
   * 设置主题
   */
  setTheme(theme) {
    this.setState({ theme })
  }

  // ========== 心情小偷相关操作 ==========

  /**
   * 添加偷取记录
   */
  addStealRecord(record) {
    this.setState({
      stealHistory: [record, ...this.state.stealHistory]
    })
  }

  /**
   * 设置偷取目标
   */
  setStealTarget(target) {
    this.setState({ stealTarget: target })
  }

  // ========== 工具方法 ==========

  /**
   * 清空所有数据
   */
  clearAll() {
    this.state = this.getInitialState()
    this.saveToStorage()
    this.notify()
  }

  /**
   * 获取用户是否已登录
   */
  isLoggedIn() {
    return this.state.userInfo.isLoggedIn
  }

  /**
   * 获取是否有伴侣
   */
  hasPartner() {
    return this.state.partnerInfo !== null
  }

  /**
   * 获取胶囊数量
   */
  getCapsuleCount() {
    return this.state.capsules.length
  }

  /**
   * 获取未解锁胶囊数量
   */
  getLockedCapsuleCount() {
    return this.state.capsules.filter(capsule => capsule.isLocked).length
  }
}

// 创建全局实例
const appStore = new AppStore()

// 导出类型和实例
// 导出store实例和类型定义
module.exports = {
  store: appStore,
  AppStore,
  default: appStore
}